<template>
  <div class="one">
    <div class="chart-wrapper">
      <div id="pieBar" class="chart-container-bar"></div>
      <div id="pieChart" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import { loss } from "./data";
import { selectWeightDay } from "@/api/progress";

// 定义饼图响应式数据
const option = ref({
  title: {
    left: "center",
    top: "0%",
    textStyle: {
      color: "#fff",
      fontSize: 18,
    },
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} {b}: {c}%",
    textStyle: {
      color: "#000",
    },
  },
  legend: {
    show: false,
    bottom: "15%",
    left: "left",
    textStyle: {
      color: "#fff",
    },
  },
  series: [
    {
      name: "",
      type: "pie",
      radius: ["30%", "60%"],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 2,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 30,
          fontWeight: "bold",
          formatter: "{b}: {c}%",
          textStyle: {
            color: "#fff",
          },
        },
      },
      label: {
        show: true,
        formatter: "{b}: {c}%",
        textStyle: {
          color: "#fff",
        },
      },
      labelLine: {
        lineStyle: {
          color: "#fff",
        },
      },
      data: [
        {
          value: 0,
          name: "干调",
        },
        {
          value: 0,
          name: "蔬菜",
        },
        {
          value: 0,
          name: "蛋类",
        },
      ],
    },
  ],
});

//// 定义柱状图响应式数据
const optionBar = ref({
  title: {
    // text: "重量对比分析",
    left: "center",
    textStyle: {
      color: "#fff",
    },
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
    textSt: {
      color: "#000",
    },
  },
  legend: {
    show: false,
    data: [],
    bottom: "0%",
    textStyle: {
      color: "#fff",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "5%",
    top: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: [],
    axisLine: {
      lineStyle: {
        color: "#fff",
      },
    },
    axisLabel: {
      color: "#fff",
    },
  },
  yAxis: {
    type: "value",
    name: "重量(G)",
    nameTextStyle: {
      color: "#fff",
    },
    axisLine: {
      lineStyle: {
        color: "#fff",
      },
    },
    axisLabel: {
      color: "#fff",
    },
    splitLine: {
      lineStyle: {
        color: "rgba(255, 255, 255, 0.2)",
      },
    },
  },
  series: [
    {
      name: "净重",
      type: "bar",
      data: [],
      itemStyle: {
        // color: "#FF6B6B"
      },
      label: {
        show: false,
        textStyle: {
          color: "#fff",
        },
      },
      emphasis: {
        label: {
          show: false,
          formatter: "{c}斤",
          textStyle: {
            color: "#fff",
          },
        },
      },
    },
    {
      name: "损耗",
      type: "bar",
      data: [],
      itemStyle: {
        // color: "#4ECDC4"
      },
      label: {
        show: true,
        position: "top",
        formatter: function (params) {
          // 从数据对象中获取百分比
          return params.data.percent + "%";
        },
        textStyle: {
          color: "#fff",
        },
      },
      emphasis: {
        label: {
          show: true,
          formatter: function (params) {
            // 显示重量和百分比
            return params.data.value + "G (" + params.data.percent + "%)";
          },
          textStyle: {
            color: "#fff",
          },
        },
      },
    },
    {
      name: "毛重",
      type: "bar",
      data: [],
      itemStyle: {
        // color: "#FFD166"
      },
      label: {
        show: false,
        textStyle: {
          color: "#fff",
        },
      },
      emphasis: {
        label: {
          show: false,
          formatter: "{c}斤",
          textStyle: {
            color: "#fff",
          },
        },
      },
    },
  ],
});

// 声明图表变量以便在函数间共享
let myChart;
let myChartBar;

// 更新图表数据的函数
const updateChartData = (data) => {
  // 更新饼图数据
  // option.value.title.text = `总重量${val}G`;
  // 计算每个种类的总重量（净重+损耗+毛重）
  // const totalWeight = val1 + val2 + val3;

  // 计算并更新饼图数据为占比（保留两位小数）
  // option.value.series[0].data[0].value = Math.round((val1 / totalWeight) * 100 * 100) / 100;
  // option.value.series[0].data[1].value = Math.round((val2 / totalWeight) * 100 * 100) / 100;
  // option.value.series[0].data[2].value = Math.round((val3 / totalWeight) * 100 * 100) / 100;

  // 更新柱状图数据
  let title = []; //类别
  let num1 = []; //净重
  let num2 = []; //毛重
  let num3 = []; //损耗
  let lossPercentages = []; //损耗占比
  let count = 0;

  selectWeightDay({
    week: data.week,
  }).then((res) => {
    if (res.code == 200) {
      // 计算总量并收集柱状图数据
      res.data.forEach((item) => {
        count += item.weightNet;
        num1.push(item.weightNet);
        num2.push(item.weightWaste);
        num3.push(item.weightGross);
        title.push(item.cateName);
      });

      // 根据总量count计算每个类型的占比并更新饼图数据
      const pieData = res.data.map((item) => ({
        name: item.cateName,
        value: Math.round((item.weightNet / count) * 100 * 100) / 100,
      }));
      option.value.series[0].data = pieData;

      res.data.forEach((item, index) => {
        const percentage =
          count > 0
            ? Math.round((item.weightWaste / count) * 100 * 100) / 100
            : 0;
        lossPercentages.push(percentage);
      });

      if (myChart) {
        myChart.setOption(option.value);
      }

      optionBar.value.series[0].data = num1;
      // 为损耗系列数据添加百分比属性
      optionBar.value.series[1].data = num2.map((value, index) => ({
        value: value,
        percent: lossPercentages[index],
      }));
      optionBar.value.series[2].data = num3;
      optionBar.value.xAxis.data = title;

      if (myChartBar) {
        myChartBar.setOption(optionBar.value);
      }

      // optionBar.value.series[0].data = res.data.netWeight
      // optionBar.value.series[1].data = res.data.lossWeight
      // optionBar.value.series[2].data = res.data.grossWeight
    }
  });

  // 计算损耗占比（损耗/总重量）并保留两位小数

  // option.value.series.data
};

// 暴露方法给父组件
defineExpose({
  updateChartData,
});

onMounted(() => {
  // 初始化饼图
  const chartDom = document.getElementById("pieChart");
  myChart = echarts.init(chartDom);
  myChart.setOption(option.value);

  // 初始化柱状图
  const chartDomBar = document.getElementById("pieBar");
  myChartBar = echarts.init(chartDomBar);
  myChartBar.setOption(optionBar.value);

  // 监听窗口大小变化，调整图表尺寸
  window.addEventListener("resize", () => {
    if (myChart) {
      myChart.resize();
    }
    if (myChartBar) {
      myChartBar.resize();
    }
  });
});
</script>

<style lang='scss' scoped>
.one {
  width: 100%;
  height: 100%;
  //   padding: 20px;
}

.chart-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
}

.chart-container-bar {
  width: 65%;
  height: 100%;
}

.chart-container {
  width: 35%;
  height: 100%;
  //   bacGround-color: #f9f9f9;
  border-radius: 8px;
}
</style>
